package com.boom.springapp.javafxdemo.utils;

/**
 * @author hhl
 * @version 1.0
 * @description
 * @date 2025/11/20 22:06
 */
//import com.fasterxml.jackson.databind.JsonNode;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClients;
//import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson2.JSON;
import com.boom.springapp.javafxdemo.common.DefaultConfiguration;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
@Getter
public class BilibiliAPI {
    private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0";
    private static final String ORIGIN = "https://www.bilibili.com";

    private String cookie;
    private CloseableHttpClient httpClient;
    private ObjectMapper objectMapper;
    private DefaultConfiguration defaultConfiguration;

    public BilibiliAPI(String cookie, DefaultConfiguration defaultConfiguration) {
        this.cookie = cookie;
        this.httpClient = HttpClients.createDefault();
        this.objectMapper = new ObjectMapper();
        this.defaultConfiguration = defaultConfiguration;
    }
    /**
     * 在请求之间添加延迟，减轻API负担，避免频繁请求导致的封禁
     *
     * @param requestType 请求类型："normal"为普通请求，"retry"为重试请求
     */
    public void sleepBetweenRequests(String requestType) {
        double delay;
        if ("retry".equals(requestType)) {
            delay = defaultConfiguration.retryDelay; // 重试延迟5秒
        } else {
            // 正常请求延迟1-2秒
            delay = defaultConfiguration.minDelay + ThreadLocalRandom.current().nextDouble(defaultConfiguration.maxDelay-defaultConfiguration.minDelay);
        }

        try {
            Thread.sleep((long) (delay * 1000));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * 统一的内容信息获取接口
     *
     * @param identifier   内容标识符（BV号、EP号或SS号）
     * @param contentType  内容类型（"video"、"bangumi"或"season"），如果不提供会自动判断
     * @return 内容信息Map
     */
    public Map<String, Object> fetchContentInfo(String identifier, String contentType) {
        // 如果未指定内容类型，则根据标识符自动判断
        if (contentType == null || contentType.isEmpty()) {
            if (identifier.startsWith("BV")) {
                contentType = "video";
            } else if (identifier.startsWith("EP")) {
                contentType = "bangumi";
            } else if (identifier.startsWith("SS")) {
                contentType = "season";
            } else {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("code", -1);
                errorResult.put("message", "无法识别的标识符格式");
                errorResult.put("data", new HashMap<>());
                return errorResult;
            }
        }

        // 根据内容类型调用相应的获取方法
        switch (contentType) {
            case "video":
                return fetchVideoInfo(identifier);
            case "bangumi":
                String epId = extractEpId(identifier);
                return fetchBangumiEpisodeInfo(epId);
            case "season":
                String seasonId = extractSeasonId(identifier);
                return fetchBangumiSeasonInfo(seasonId);
            default:
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("code", -1);
                errorResult.put("message", "不支持的内容类型");
                errorResult.put("data", new HashMap<>());
                return errorResult;
        }
    }

    // 重载方法，允许不传contentType参数
    public Map<String, Object> fetchContentInfo(String identifier) {
        return fetchContentInfo(identifier, null);
    }

    /**
     * 从SS标识符中提取数字ID
     *
     * @param identifier SS标识符
     * @return 数字ID
     */
    private String extractSeasonId(String identifier) {
        if (identifier.startsWith("SS")) {
            return identifier.substring(2);
        }
        return identifier;
    }

    /**
     * 从EP标识符中提取数字ID
     *
     * @param identifier EP标识符
     * @return 数字ID
     */
    private String extractEpId(String identifier) {
        if (identifier.startsWith("EP")) {
            return identifier.substring(2);
        }
        return identifier;
    }


    /**
     * 获取评论总数
     *
     * @param oid 视频ID
     * @return 评论总数
     */
    public int fetchCommentCount(String oid) {
        String url = "https://api.bilibili.com/x/v2/reply/count?type=1&oid=" + oid;

        try {
            sleepBetweenRequests("normal");

            HttpGet request = new HttpGet(url);
            request.setHeader("User-Agent", USER_AGENT);
            request.setHeader("Referer", ORIGIN);
            request.setHeader("Accept", "application/json, text/plain, */*");

            if (cookie != null && !cookie.isEmpty()) {
                request.setHeader("Cookie", cookie);
            }

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    return 0;
                }

                String contentEncoding = response.getFirstHeader("Content-Encoding") != null ?
                        response.getFirstHeader("Content-Encoding").getValue() : "none";

                String responseBody = EntityUtils.toString(response.getEntity());

                JsonNode data = objectMapper.readTree(responseBody);
                if (data.has("code") && data.get("code").asInt() == 0) {
                    return data.get("data").get("count").asInt();
                }
            }

        } catch (Exception e) {
            log.info("获取评论总数出错", e);
        }

        return 0;
    }

    /**
     * 获取单个视频的详细信息，包括标题
     *
     * @param bvid BV号
     * @return 包含视频信息的Map
     */
    public Map<String, Object> fetchVideoInfo(String bvid) {
        sleepBetweenRequests("normal");

        String url = "https://api.bilibili.com/x/web-interface/view?bvid=" + bvid;

        try {
            HttpGet request = new HttpGet(url);
            request.setHeader("User-Agent", USER_AGENT);
            request.setHeader("Referer", "https://www.bilibili.com/video/" + bvid);
            request.setHeader("Accept", "application/json, text/plain, */*");

            if (cookie != null && !cookie.isEmpty()) {
                request.setHeader("Cookie", cookie);
            }

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    JsonNode data = objectMapper.readTree(responseBody);

                    Map<String, Object> result = new HashMap<>();
                    result.put("code", data.get("code").asInt());
                    result.put("data", data.get("data"));
                    return result;
                }
            }

        } catch (Exception e) {
            log.info("获取视频信息出错", e);
        }

        Map<String, Object> errorResult = new HashMap<>();
        errorResult.put("code", -1);
        errorResult.put("message", "获取视频信息出错");
        errorResult.put("data", new HashMap<>());
        return errorResult;
    }

    /**
     * 获取评论列表
     *
     * @param oid       视频ID
     * @param nextPage  页码
     * @param order     排序方式
     * @param offsetStr 偏移量
     * @return 包含评论信息的Map
     */
    public Map<String, Object> fetchComments(String oid, int nextPage, int order, String offsetStr) {
        sleepBetweenRequests("normal");

        // 构建格式化的offset字符串
        String fmtOffsetStr;
        if (offsetStr == null || offsetStr.isEmpty()) {
            fmtOffsetStr = "{\"offset\":\"\"}";
        } else {
            // 使用JSON转义处理offsetStr
            fmtOffsetStr = "{\"offset\":\"" + escapeJson(offsetStr) + "\"}";
        }

        // 构建旧接口URL
        String params = String.format("oid=%s&type=1&pn=%d&sort=%d", oid, nextPage, order);
        String url = "https://api.bilibili.com/x/v2/reply?" + params;

        log.info("获取评论列表: {}", url);

        try {
            HttpGet request = new HttpGet(url);
            request.setHeader("User-Agent", USER_AGENT);
            request.setHeader("Referer", ORIGIN);
            request.setHeader("Accept", "application/json, text/plain, */*");

            if (cookie != null && !cookie.isEmpty()) {
                request.setHeader("Cookie", cookie);
            }

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                log.info("获取评论列表的状态码: {}", statusCode);

                if (statusCode == 200) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    Map<String, Object> data = objectMapper.readValue(responseBody, new TypeReference<Map<String, Object>>() {});

                    log.debug("评论接口请求成功: {}", data.get("code"));

                    // 直接返回完整的响应数据，保持与Python代码一致
                    return data;
                } else {
                    String responseText = JSON.toJSONString(response);
                    if (responseText.length() > 200) {
                        responseText = responseText.substring(0, 200);
                    }
                    log.error("评论接口请求失败: {} - {}", statusCode, responseText);
                }
            }

        } catch (Exception e) {
            log.error("获取评论列表出错", e);
        }

        // 如果旧接口失败，尝试新接口
        try {
            sleepBetweenRequests("retry");

            // 构建新接口参数
            String wbiParams = String.format(
                    "oid=%s&type=1&mode=3&plat=1&web_location=1315875&pagination_str=%s",
                    oid, URLEncoder.encode(fmtOffsetStr, "UTF-8")
            );

            String wbiUrl = "https://api.bilibili.com/x/v2/reply/wbi/main?" + wbiParams;

            log.info("尝试使用WBI接口获取评论: {}", wbiUrl);

            // 假设有signAndGenerateUrl方法
            String signedUrl = CryptoUtils.signAndGenerateUrl(wbiUrl, cookie);

            HttpGet wbiRequest = new HttpGet(signedUrl);
            wbiRequest.setHeader("User-Agent", USER_AGENT);
            wbiRequest.setHeader("Referer", ORIGIN);
            wbiRequest.setHeader("Accept", "application/json, text/plain, */*");

            if (cookie != null && !cookie.isEmpty()) {
                wbiRequest.setHeader("Cookie", cookie);
            }

            try (CloseableHttpResponse wbiResponse = httpClient.execute(wbiRequest)) {
                wbiResponse.getStatusLine().getStatusCode();
                wbiResponse.getEntity().getContent(); // 确保状态检查后处理响应
                String wbiResponseBody = EntityUtils.toString(wbiResponse.getEntity());

                return objectMapper.readValue(wbiResponseBody, new TypeReference<Map<String, Object>>() {});
            }

        } catch (Exception e) {
            log.error("WBI接口获取评论列表出错", e);
        }

        // 返回错误结果
        Map<String, Object> errorResult = new HashMap<>();
        errorResult.put("code", -1);
        errorResult.put("message", "获取评论列表出错");
        errorResult.put("data", Collections.singletonMap("replies", new ArrayList<>()));
        return errorResult;
    }

    // JSON转义辅助方法
    private String escapeJson(String input) {
        if (input == null) {
            return null;
        }
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    /**
     * 获取子评论
     *
     * @param oid      视频ID
     * @param rpid     评论ID
     * @param nextPage 页码
     * @return 包含子评论信息的Map
     */
    public Map<String, Object> fetchSubComments(String oid, long rpid, int nextPage) {
        sleepBetweenRequests("normal");

        String params = String.format("oid=%s&type=1&root=%d&ps=20&pn=%d", oid, rpid, nextPage);
        String url = "https://api.bilibili.com/x/v2/reply/reply?" + params;

        try {
            // 对URL进行签名
            String signedUrl = CryptoUtils.signAndGenerateUrl(url, this.cookie);

            HttpGet request = new HttpGet(signedUrl);
            request.setHeader("User-Agent", USER_AGENT);
            request.setHeader("Referer", ORIGIN);
            request.setHeader("Accept", "application/json, text/plain, */*");

            if (cookie != null && !cookie.isEmpty()) {
                request.setHeader("Cookie", cookie);
            }

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();

                if (statusCode == 200) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    Map<String, Object> data = objectMapper.readValue(responseBody, new TypeReference<Map<String, Object>>() {});
                    return data;
                } else {
                    // 如果状态码不是200，抛出异常以便进入异常处理
                    throw new RuntimeException("HTTP请求失败，状态码: " + statusCode);
                }
            }

        } catch (Exception e) {
            log.error("获取子评论出错: {}", e.getMessage(), e);

            // 失败重试前添加延迟
            sleepBetweenRequests("retry");

            // 返回错误结果
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", -1);
            errorResult.put("message", e.getMessage());
            errorResult.put("data", Collections.singletonMap("replies", new ArrayList<>()));
            return errorResult;
        }
    }

    /**
     * 获取番剧剧集信息
     *
     * @param epId 剧集ID（数字）
     * @return 包含剧集信息的Map，包括aid等
     */
    public Map<String, Object> fetchBangumiEpisodeInfo(String epId) {
        sleepBetweenRequests("normal");

        String url = "https://api.bilibili.com/pgc/view/web/season";
        String fullUrl = url + "?ep_id=" + epId;

        try {
            HttpGet request = new HttpGet(fullUrl);
            request.setHeader("User-Agent", USER_AGENT);
            request.setHeader("Referer", "https://www.bilibili.com/bangumi/play/ep" + epId);
            request.setHeader("Accept", "application/json, text/plain, */*");
            request.setHeader("Origin", ORIGIN);

            if (cookie != null && !cookie.isEmpty()) {
                request.setHeader("Cookie", cookie);
            }

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                log.info("获取番剧剧集信息的状态码: " + statusCode);

                if (statusCode == 200) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    JsonNode data = objectMapper.readTree(responseBody);

                    if (data.has("code") && data.get("code").asInt() == 0) {
                        JsonNode resultNode = data.get("result");
                        JsonNode episodesNode = resultNode.get("episodes");

                        JsonNode currentEpisode = null;
                        if (episodesNode != null && episodesNode.isArray()) {
                            for (JsonNode ep : episodesNode) {
                                if (ep.has("id") && String.valueOf(ep.get("id").asLong()).equals(epId)) {
                                    currentEpisode = ep;
                                    break;
                                }
                            }
                        }

                        if (currentEpisode == null) {
                            log.error("未找到EP" + epId + "的信息");
                            Map<String, Object> errorResult = new HashMap<>();
                            errorResult.put("code", -1);
                            errorResult.put("message", "未找到对应剧集");
                            errorResult.put("data", new HashMap<>());
                            return errorResult;
                        }

                        // 构造类似视频信息的返回格式
                        Map<String, Object> resultData = new HashMap<>();
                        resultData.put("aid", currentEpisode.has("aid") ? currentEpisode.get("aid").asLong() : 0);
                        resultData.put("bvid", currentEpisode.has("bvid") ? currentEpisode.get("bvid").asText() : "");

                        String title = "";
                        if (currentEpisode.has("long_title") && !currentEpisode.get("long_title").asText().isEmpty()) {
                            title = currentEpisode.get("long_title").asText();
                        } else if (currentEpisode.has("share_copy")) {
                            title = currentEpisode.get("share_copy").asText();
                        }
                        resultData.put("title", title);

                        resultData.put("desc", currentEpisode.has("desc") ? currentEpisode.get("desc").asText() : "");

                        Map<String, Object> owner = new HashMap<>();
                        JsonNode upInfo = resultNode.has("up_info") ? resultNode.get("up_info") : null;
                        owner.put("mid", upInfo != null && upInfo.has("mid") ? upInfo.get("mid").asLong() : 0);
                        owner.put("name", upInfo != null && upInfo.has("uname") ? upInfo.get("uname").asText() : "");
                        resultData.put("owner", owner);

                        resultData.put("stat", currentEpisode.has("stat") ? currentEpisode.get("stat") : new HashMap<>());
                        resultData.put("ep_id", epId);
                        resultData.put("season_id", resultNode.has("season_id") ? resultNode.get("season_id").asText() : "");
                        resultData.put("series_title", resultNode.has("title") ? resultNode.get("title").asText() : "");

                        Map<String, Object> result = new HashMap<>();
                        result.put("code", 0);
                        result.put("data", resultData);

                        log.info("成功获取番剧EP" + epId + "信息: " + title);
                        return result;
                    } else {
                        log.error("获取番剧剧集信息失败: " + data.toString());
                        Map<String, Object> errorResult = new HashMap<>();
                        errorResult.put("code", -1);
                        errorResult.put("message", data.has("message") ? data.get("message").asText() : "未知错误");
                        errorResult.put("data", new HashMap<>());
                        return errorResult;
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取番剧剧集信息出错: {}", e.getMessage(), e);
        }

        Map<String, Object> errorResult = new HashMap<>();
        errorResult.put("code", -1);
        errorResult.put("message", "获取番剧剧集信息出错");
        errorResult.put("data", new HashMap<>());
        return errorResult;
    }

    /**
     * 获取番剧季度信息
     *
     * @param seasonId 季度ID（数字）
     * @return 包含季度信息的Map，包括第一集的aid等
     */
    public Map<String, Object> fetchBangumiSeasonInfo(String seasonId) {
        sleepBetweenRequests("normal");

        String url = "https://api.bilibili.com/pgc/view/web/season";
        String fullUrl = url + "?season_id=" + seasonId;

        try {
            HttpGet request = new HttpGet(fullUrl);
            request.setHeader("User-Agent", USER_AGENT);
            request.setHeader("Referer", "https://www.bilibili.com/bangumi/play/ss" + seasonId);
            request.setHeader("Accept", "application/json, text/plain, */*");
            request.setHeader("Origin", ORIGIN);

            if (cookie != null && !cookie.isEmpty()) {
                request.setHeader("Cookie", cookie);
            }

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                log.info("获取番剧季度信息的状态码: " + statusCode);

                if (statusCode == 200) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    JsonNode data = objectMapper.readTree(responseBody);

                    if (data.has("code") && data.get("code").asInt() == 0) {
                        JsonNode resultNode = data.get("result");
                        JsonNode episodesNode = resultNode.has("episodes") ? resultNode.get("episodes") : null;

                        if (episodesNode == null || !episodesNode.isArray() || episodesNode.size() == 0) {
                            log.error("SS" + seasonId + "没有找到剧集信息");
                            Map<String, Object> errorResult = new HashMap<>();
                            errorResult.put("code", -1);
                            errorResult.put("message", "未找到剧集");
                            errorResult.put("data", new HashMap<>());
                            return errorResult;
                        }

                        // 使用第一集的信息
                        JsonNode firstEpisode = episodesNode.get(0);

                        // 构造类似视频信息的返回格式
                        Map<String, Object> resultData = new HashMap<>();
                        resultData.put("aid", firstEpisode.has("aid") ? firstEpisode.get("aid").asLong() : 0);
                        resultData.put("bvid", firstEpisode.has("bvid") ? firstEpisode.get("bvid").asText() : "");
                        resultData.put("title", resultNode.has("title") ? resultNode.get("title").asText() : ""); // 使用季度标题
                        resultData.put("desc", resultNode.has("evaluate") ? resultNode.get("evaluate").asText() : "");

                        Map<String, Object> owner = new HashMap<>();
                        JsonNode upInfo = resultNode.has("up_info") ? resultNode.get("up_info") : null;
                        owner.put("mid", upInfo != null && upInfo.has("mid") ? upInfo.get("mid").asLong() : 0);
                        owner.put("name", upInfo != null && upInfo.has("uname") ? upInfo.get("uname").asText() : "");
                        resultData.put("owner", owner);

                        resultData.put("stat", firstEpisode.has("stat") ? firstEpisode.get("stat") : new HashMap<>());
                        resultData.put("season_id", seasonId);
                        resultData.put("ep_id", firstEpisode.has("id") ? firstEpisode.get("id").asLong() : 0);
                        resultData.put("series_title", resultNode.has("title") ? resultNode.get("title").asText() : "");
                        resultData.put("total_episodes", episodesNode.size());

                        Map<String, Object> result = new HashMap<>();
                        result.put("code", 0);
                        result.put("data", resultData);

                        log.info("成功获取番剧SS" + seasonId + "信息: " +
                                resultData.get("title") + " (共" + episodesNode.size() + "集)");
                        return result;
                    } else {
                        log.error("获取番剧季度信息失败: " + data.toString());
                        Map<String, Object> errorResult = new HashMap<>();
                        errorResult.put("code", -1);
                        errorResult.put("message", data.has("message") ? data.get("message").asText() : "未知错误");
                        errorResult.put("data", new HashMap<>());
                        return errorResult;
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取番剧季度信息出错: {}", e.getMessage(), e);
        }

        Map<String, Object> errorResult = new HashMap<>();
        errorResult.put("code", -1);
        errorResult.put("message", "获取番剧季度信息出错");
        errorResult.put("data", new HashMap<>());
        return errorResult;
    }

    /**
     * 获取UP主视频列表
     *
     * @param mid   UP主ID
     * @param page  页码
     * @param order 排序方式
     * @return 包含视频列表信息的Map
     */
    public Map<String, Object> fetchVideoList(long mid, int page, String order) {
        // 请求前添加延迟
        sleepBetweenRequests("normal");

        // 构建URL参数
        Map<String, String> params = new HashMap<>();
        params.put("mid", String.valueOf(mid));
        params.put("order", order);
        params.put("platform", "web");
        params.put("pn", String.valueOf(page));
        params.put("ps", "30");
        params.put("tid", "0");

        StringBuilder urlBuilder = new StringBuilder("https://api.bilibili.com/x/space/wbi/arc/search?");
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (!first) {
                urlBuilder.append("&");
            }
            urlBuilder.append(entry.getKey()).append("=").append(entry.getValue());
            first = false;
        }
        String url = urlBuilder.toString();

        try {
            log.info("获取UP主 " + mid + " 的视频列表: 页码=" + page + ", 排序=" + order);

            // 生成签名URL
            String signedUrl = CryptoUtils.signAndGenerateUrl(url, cookie);

            HttpGet request = new HttpGet(signedUrl);
            request.setHeader("User-Agent", USER_AGENT);
            request.setHeader("Referer", "https://space.bilibili.com/" + mid + "/video");
            request.setHeader("Accept", "application/json, text/plain, */*");
            request.setHeader("Origin", ORIGIN);

            if (cookie != null && !cookie.isEmpty()) {
                request.setHeader("Cookie", cookie);
            }

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                log.info("获取视频列表的状态码: " + statusCode);

                if (statusCode == 200) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    JsonNode data = objectMapper.readTree(responseBody);

                    if (data.has("code") && data.get("code").asInt() == 0) {
                        return objectMapper.convertValue(data, new TypeReference<Map<String, Object>>() {});
                    } else {
                        String errorMsg = data.has("message") ? data.get("message").asText() : "未知错误";
                        log.error("获取UP主视频列表失败: " + errorMsg);
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取UP主视频列表出错: " + e.getMessage());
            e.printStackTrace();
        }

        // 返回错误结果
        Map<String, Object> errorResult = new HashMap<>();
        errorResult.put("code", -1);
        errorResult.put("message", "获取UP主视频列表出错");

        Map<String, Object> data = new HashMap<>();
        Map<String, Object> list = new HashMap<>();
        list.put("vlist", new ArrayList<>());
        data.put("list", list);
        errorResult.put("data", data);

        return errorResult;
    }


    public void close() throws IOException {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}
